import { s_getPostWareInfo, s_getTableInfo, s_operateInfo, s_updateInfo } from "@/services/basis";
import { getSelection } from "@/services/selections";
import { ActionType, ProCard, ProColumns, ProForm, ProFormDatePicker, ProFormInstance, ProFormItem, ProFormRadio, ProFormSelect, ProFormText, ProTable, TableDropdown } from "@ant-design/pro-components";
import { useRequest } from "@umijs/max";
import { Button, Card, Col, message, Modal, Row, Space, Table, TableColumnProps, Tabs, TabsProps, Tag, Typography } from "antd";
import moment from "moment";
import React, { useRef, useState } from "react";

const App:React.FC=()=>{
    const [selectedRowKeys,setSelectedRowKeys]=useState<React.Key[]>([]);
    const [selectedRows,setSelectedRows]=useState<DataType[]>([]);
    const [open,setOpen]=useState(false);

    const [selectedRowKeys2,setSelectedRowKeys2]=useState<React.Key[]>([]);
    const [selectedRows2,setSelectedRows2]=useState<DataType2[]>([]);
    const [open2,setOpen2]=useState(false);
    const [selectedRecord2,setSelectedRecord2]=useState<DataType2[]>([]);

    const [jobSelection,setJobSelection]=useState([]);
    const [sampleItemSelection,setSampleItemSelection]=useState([]);

    const [tabKey,setTabKey]=useState('1');
    const [etype,setEtype]=useState(1);

    const table_ref=useRef<ActionType>();
    const table_ref2=useRef<ActionType>();
    const form_ref=useRef<ProFormInstance>();
    const form_ref2=useRef<ProFormInstance>();

    //岗位表
    useRequest(()=>getSelection({source:'base_job',x_id:1}),{
       onSuccess:(data:any)=>{
           const x=data.map((item:any)=>({value:item.id,label:item.name}));
          setJobSelection(x);
      }
    });

    //样品过程项目表
    useRequest(()=>getSelection({source:'base_sample_item',x_id:1}),{
        onSuccess:(data:any)=>{
          const x=data.map((item:any)=>({value:item.id,label:item.name}));
          setSampleItemSelection(x);
        }
    });


    interface DataType{
        id:number,
        x_id:number,
        code:string,
        name:string,
        describ:string,
        operate_time:string,
        operater_id:string,
        operater_name:string,
        status:number,
    }
    const columns:ProColumns<DataType>[]=[
        {key:'id',dataIndex:'id', hidden:true},
        { dataIndex:'operater_id', hidden:true},
        {dataIndex:'code',title:'项目编码'},
        {dataIndex:'name',title:'项目名称'},
        {dataIndex:'describ',title:'项目描述'},
        {dataIndex:'operate_time',title:'修改时间',
            render:(text)=>moment(moment(text?.toString()).toDate()).format('YYYY-MM-DD')},
        {dataIndex:'operater_name',title:'修改人'},
        {dataIndex:'status',title:'状态',
            render:(text)=>text==1?<>正常</>:text==2?<Tag style={{color:'blue'}}>冻结</Tag>:<Tag style={{color:'red'}}>删除</Tag>},
    ];
  
    interface DataType2{
        x_id:number,
        id:number,
        code:string,
        name:string,
        step1:string,step2:string,step3:string,step4:string,step5:string,step6:string,
        operate_time:string,status:1,
    }

    const columns2:ProColumns<DataType2>[]=[
        {dataIndex:'x_id',hidden:true},
        {dataIndex:'id',hidden:true},
        {dataIndex:'code',title:'过程编码'},
        {dataIndex:'name',title:'过程名称'},
        {dataIndex:'step1',title:'阶段一'},{dataIndex:'step2',title:'阶段二'},{dataIndex:'step3',title:'阶段三'},
        {dataIndex:'step4',title:'阶段四'},{dataIndex:'step5',title:'阶段五'},{dataIndex:'step6',title:'阶段六'},
        {dataIndex:'operate_time',title:'操作时间',
            render:(text:any)=>moment(moment(text).toDate()).format('YYYY-MM-DD')
        },
        {dataIndex:'status',title:'状态',
            render:(text)=>text==1?<>正常</>:text==2?<Tag style={{color:'blue'}}>冻结</Tag>:<Tag style={{color:'red'}}>删除</Tag>},
    ];
    
    const items:TabsProps['items']=[
      {
        key:'1',
        label:'样品项目',
        children:<>
        {/* {JSON.stringify(selectedRows)} */}
            <ProTable<DataType>
                rowKey='id'
                actionRef={table_ref}
                search={false}
                columns={columns}
                rowSelection={{
                    type:'radio',
                    onChange:(selectedRowKeys,selectedRows)=>{
                            setSelectedRowKeys(selectedRowKeys);
                            setSelectedRows(selectedRows);
                    },
                }}
                request={async (params)=>{
                    //const id=selectedRowKeys.length==0?0:selectedRowKeys[0];
                    const x=await s_getTableInfo({source:'v_sample_item',x_id:1,id:0})
                    return{
                        data:x.data,
                        success:true,
                    }
                }}
                scroll={{
                    y:430,
                }}
                pagination={{
                    pageSize:9,
                }}
                />
        </>
      },{
         key:'2',
         label:'样品过程',
         children:<>
           <ProTable<DataType2> 
            rowKey='id'
             search={false}
             actionRef={table_ref2}
             columns={columns2}
             rowSelection={{
                 type:'radio',
                 onChange:(selectedRowKeys,selectedRows:any)=>{
                         setSelectedRowKeys2(selectedRowKeys);
                         setSelectedRows2(selectedRows);
                 },
             }}
             request={async (params)=>{
                 //const id=selectedRowKeys.length==0?0:selectedRowKeys[0];
                 const x=await s_getPostWareInfo({source:'v_sample_progress',x_id:1,id:0})
                 return{
                     data:x.data,
                     success:true,
                 }
             }}
             scroll={{
                y:430,
            }}
            pagination={{
                pageSize:9,
            }}
        
           />
         </>
      },
    ];

    async function add(){
        setEtype(1);
        if(tabKey=='1'){
          setOpen(true);
          setOpen2(false);
        }else{
            setOpen2(true);
            setOpen(false);
          }
    };
    async function edit(){
        if(tabKey=='1'){
            // setSelectedRows2([]);
           if(selectedRows.length==0)
              message.warning('请先选择要编辑的行。');
            else{
                // alert('6666');
                setOpen(true);
                setOpen2(false);
                setEtype(0);
            }
        }else{
            // 编辑样品过程，需从后台重新取数
            if(selectedRows2.length==0)
                message.warning('请先选择要编辑的行。');
              else{
                 //按ID取数
                  const x=await s_getTableInfo({source:'base_sample_progress',x_id:1,id:selectedRowKeys2[0]});
                  setSelectedRecord2(x.data);
                //   alert(JSON.stringify(x.data));
                  setOpen2(true);
                  setOpen(false);
                  setEtype(0);
              }
        }
    };

    async function save(){
        if(tabKey=='1'){
           const fdata2=form_ref?.current?.getFieldsValue();
           const fdata={...fdata2,
                 operate_time:moment().format('YYYY-MM-DD HH:00:00'),
           };
           const x=await s_updateInfo({source:'base_sample_item',x_id:1,operater_id:1,etype,fdata});
           
           if(x.success){
              message.success('数据保存成功。');
              setOpen(false);
              table_ref.current?.reloadAndRest?.();
              setSelectedRows([]);
              setSelectedRowKeys([]);
              setEtype(1);
           }else
               message.error('数据保存失败。');
        }else{
        //样品过程保存
        const fdata2=form_ref2?.current?.getFieldsValue();
        const fdata={...fdata2,
              operate_time:moment().format('YYYY-MM-DD HH:00:00'),
        };
        // alert(JSON.stringify(fdata));
        const x=await s_updateInfo({source:'base_sample_progress',x_id:1,operater_id:1,etype,fdata});
        if(x.success){
           message.success('数据保存成功。');
           setOpen2(false);
           table_ref2.current?.reloadAndRest?.();
           setSelectedRows2([]);
           setSelectedRowKeys2([]);
           setEtype(1);
        }else
        message.error('数据保存失败。');
        }
    };

    async function operate(otype:number){
          setEtype(1);
          var id=0;
          if(tabKey=='1'){
             if(selectedRows.length==0)
                 message.warning('请先选择要操作的行。');
             else{
                 id=selectedRows[0].id;
                const x=await s_operateInfo({source:'base_sample_item',x_id:1,operater_id:1,otype,id});
                if(x.success){
                    message.success('数据更新成功。');
                    table_ref.current?.reloadAndRest?.();
                    setSelectedRows([]);
                    setSelectedRowKeys([]);
                }
                else
                    message.error('数据更新失败。');
                
               }
        }
        else{
            if(selectedRows2.length==0)
                message.warning('请先选择要操作的行。');
            else{
                id=selectedRows2[0]?.id;
                const x=await s_operateInfo({source:'base_sample_progress',x_id:1,operater_id:1,otype,id});
                if(x.success){
                    message.success('数据更新成功。');
                    table_ref2.current?.reloadAndRest?.();
                    setSelectedRows2([]);
                    setSelectedRowKeys2([]);
                }
                else
                    message.error('数据更新失败。');
               }
        }
     };   

    return (
        <>
        <ProCard title='样品过程管理' style={{height:700,overflow:'auto'}} 
              extra={<Space>
                <Button onClick={()=>add()}>新 增</Button>
                <Button onClick={()=>edit()}>编 辑</Button>
                <Button onClick={()=>operate(2)}>冻 结</Button>
                <Button onClick={()=>operate(3)}>删 除</Button>
                <Button onClick={()=>operate(1)}>恢 复</Button>
               </Space>}
        >
       <Tabs items={items} 
            onChange={(e)=>{
                 setTabKey(e);
                 setEtype(1);
            }} 
        />
        </ProCard>
        {/* 档案增减表单 */}
        <Modal open={open} title={etype==0?'编辑样品项目':'新增样品项目'} closable destroyOnClose 
              okButtonProps={{hidden:true}}  cancelButtonProps={{hidden:true}}
              width={660} onClose={()=>setOpen(false)} onCancel={()=>setOpen(false)} > 
           <ProCard extra={<Space>
                         <Button onClick={()=>form_ref.current?.submit()}>保存</Button>
                         <Button onClick={()=>setOpen(false)}>取消</Button>
                    </Space>}>
           <ProForm 
                   formRef={form_ref} 
                   submitter={false}
                   onFinish={()=>save()}
                   initialValues={etype==0&&tabKey=='1'?{
                   ...selectedRows[0],
                   operate_time:moment(moment(selectedRows[0].operate_time).toDate()).format('YYYY-MM-DD'),
                 }:{
                    operate_time:moment().format('YYYY-MM-DD'),operater_name:'张飞飞',status:1, 
                  }}
           >
             <ProFormText name='id' hidden/>
             <ProFormText name='code' label='项目编码' rules={[{required:true,message:'必输项'}]}/>
             <ProFormText name='name' label='项目名称' rules={[{required:true,message:'必输项'}]}/>
             <ProFormText name='describ' label='作用描述' rules={[{required:true,message:'必输项'}]}/>
              
             <ProFormRadio.Group name='status' label='状态'
                options={[{label:'正常',value:1},{label:'冻结',value:2,style:{color:'blue'}},
                          {label:'删除',value:3,style:{color:'red'}}]}
             />
             <ProFormDatePicker name='operate_time' label='操作时间'/>
             <ProFormText name='operater_name' label='操作人'/>
           </ProForm>
           </ProCard>
        </Modal>
         {/* 样品过程方案-增减表单 */}
         <Modal open={open2} title={etype==0?'编辑样品过程':'新增样品过程'} closable destroyOnClose
                   okButtonProps={{hidden:true}}  cancelButtonProps={{hidden:true}}
                   width={'80%'}> 
           <ProCard extra={<Space>
                        <Button onClick={()=>form_ref2.current?.submit()}>保存</Button>
                        <Button onClick={()=>setOpen2(false)}>取消</Button>
                   </Space>}>
           <ProForm 
                   formRef={form_ref2} 
                   submitter={false}
                   onFinish={()=>save()}
                   initialValues={etype==0&&tabKey=='2'?{
                    step1_hasaddition:2,step2_hasaddition:2,step3_hasaddition:2,
                     step4_hasaddition:2,step5_hasaddition:2,step6_hasaddition:2,
                    ...selectedRecord2[0],
                    operate_time:moment(moment(selectedRecord2[0]?.operate_time).toDate()).format('YYYY-MM-DD'),
                  }:{
                     operate_time:moment().format('YYYY-MM-DD'),operater_id:1,status:1,
                     step1_hasaddition:2,step2_hasaddition:2,step3_hasaddition:2,
                     step4_hasaddition:2,step5_hasaddition:2,step6_hasaddition:2,
                   }}
           >
             <ProFormText name='id' hidden/>
             <Row gutter={8}>
                <Col span={12}>
                   <ProFormText name='code' label='过程编码' rules={[{required:true,message:'必须输入'}]}/>
                </Col>
                <Col span={12}>
                   <ProFormText name='name' label='过程名称' rules={[{required:true,message:'必须输入'}]}/>
                </Col>
             </Row>
             <Row gutter={8}>
                <Col span={12}><Typography.Text >样品过程项</Typography.Text></Col>
                <Col span={6}><Typography.Text>附件管理</Typography.Text></Col>
                <Col span={6}><Typography.Text>审批岗位</Typography.Text></Col>
             </Row>
             <Row gutter={8}>
                <Col span={12}>
                     <ProFormSelect name='step1_itemid' label='阶段一' 
                          request={async ()=>sampleItemSelection}
                     />
                </Col>
                <Col span={6}>
                     <ProFormRadio.Group name='step1_hasaddition' label='一'
                        options={[{value:1,label:'必传附件'},{value:2,label:'不限制'}]}
                     />
                </Col>
                <Col span={6}>
                     <ProFormSelect name='step1_verify_jobid' label='一' 
                       request={async ()=>jobSelection}
                     />
                </Col>
             </Row>
             <Row gutter={8}>
                <Col span={12}>
                     <ProFormSelect name='step2_itemid' label='阶段二' 
                         request={async ()=>sampleItemSelection}
                     />
                </Col>
                <Col span={6}>
                     <ProFormRadio.Group name='step2_hasaddition'   label='二'
                        options={[{value:1,label:'必传附件'},{value:2,label:'不限制'}]}
                     />
                </Col>
                <Col span={6}>
                     <ProFormSelect name='step2_verify_jobid'   label='二' request={async ()=>jobSelection}/>
                </Col>
             </Row>
             <Row gutter={8}>
                <Col span={12}>
                     <ProFormSelect name='step3_itemid' label='阶段三'  
                        request={async ()=>sampleItemSelection}
                     />
                </Col>
                <Col span={6}>
                     <ProFormRadio.Group name='step3_hasaddition'   label='三'
                        options={[{value:1,label:'必传附件'},{value:2,label:'不限制'}]}
                     />
                </Col>
                <Col span={6}>
                     <ProFormSelect name='step3_verify_jobid'  label='三'  request={async ()=>jobSelection}/>
                </Col>
             </Row>
             <Row gutter={8}>
                <Col span={12}>
                     <ProFormSelect name='step4_itemid' label='阶段四'  
                        request={async ()=>sampleItemSelection}
                     />
                </Col>
                <Col span={6}>
                     <ProFormRadio.Group name='step4_hasaddition'   label='四'
                        options={[{value:1,label:'必传附件'},{value:2,label:'不限制'}]}
                     />
                </Col>
                <Col span={6}>
                     <ProFormSelect name='step4_verify_jobid'    label='四'  request={async ()=>jobSelection}/>
                </Col>
             </Row>
             <Row gutter={8}>
                <Col span={12}>
                     <ProFormSelect name='step5_itemid' label='阶段五'  
                      request={async ()=>sampleItemSelection}
                     />
                </Col>
                <Col span={6}>
                     <ProFormRadio.Group name='step5_hasaddition'   label='五'
                        options={[{value:1,label:'必传附件'},{value:2,label:'不限制'}]}
                     />
                </Col>
                <Col span={6}>
                     <ProFormSelect name='step5_verify_jobid'   label='五' request={async ()=>jobSelection}/>
                </Col>
             </Row>
             <Row gutter={8}>
                <Col span={12}>
                     <ProFormSelect name='step6_itemid' label='阶段六'  
                      request={async ()=>sampleItemSelection}
                     />
                </Col>
                <Col span={6}>
                     <ProFormRadio.Group name='step6_hasaddition'   label='六'
                        options={[{value:1,label:'必传附件'},{value:2,label:'不限制'}]}
                     />
                </Col>
                <Col span={6}>
                     <ProFormSelect name='step6_verify_jobid'   label='六' request={async ()=>jobSelection}/>
                </Col>
             </Row>
             <Row gutter={8}>
                <Col span={8}>
                   <ProFormRadio.Group name='status' label='状态'
                         options={[{label:'正常',value:1},{label:'冻结',value:2,style:{color:'blue'}},{label:'删除',value:3,style:{color:'red'}}]}
                   />
                </Col>
                <Col span={8}>
                      <ProFormDatePicker name='operate_time' label='操作时间'/>
                </Col>
                <Col span={8}>
                      <ProFormText name='operater_name' label='操作人'/>
                </Col>
             </Row>            
             
            
             
           </ProForm>
           </ProCard>
        </Modal>
        </>
    );
}

export default App;